package com.info.threads;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.net.operation.TerServer;

import com.info.dbase.Connections;
import com.info.dbase.ExecuteSql;
import com.info.server.Event;
import com.info.utils.ConfigManager;
import com.info.utils.StringTools;

/**
 * @author HAHA
 * 
 */
public class ExecuteThread extends Thread {
	private static Logger logger = Logger.getLogger(ExecuteThread.class);
	private ExecuteSql execute = null;
	private Vector<Event> msglist = new Vector<Event>();
	private Event msg = new Event();
	private int interval = 5;
	private static BigDecimal laloSum=new BigDecimal(0);
	public static Hashtable<String, BigDecimal> runtimeLALO=new Hashtable<String, BigDecimal>();
	
	public ExecuteThread() {
	}

	public synchronized void addMsg(Event obj) {
		try {
			this.msglist.add(obj);
		} catch (Exception x) {
			logger.error("SHW#  "+x.getMessage());
			x.printStackTrace();
		}
	}

	private void extuteSql(String[] sql,boolean downFlag){
		if (this.execute == null)
			this.execute = new ExecuteSql();
		Connection conn = null;
		try {
			conn = Connections.getConnection();
			this.execute.executeSqlBat(sql, conn);
			if(downFlag){
				GetPutInfoThread gpi=new GetPutInfoThread();
				gpi.extuteSql();}
		} catch (Exception e) {
			//logger.error("SHW#" + getName() + "数据库处理出错" + e.getMessage());
			logger.error("SHW#" + sql[0]);
			e.printStackTrace();
			Connections.close(conn);
		} finally {
			Connections.close(conn);
		}
	}
	
	private String[] getLALO(String la,String lo) throws SQLException{
		if (this.execute == null)
			this.execute = new ExecuteSql();
		String[] lalo=new String[4];
		ResultSet rs = null;
		String sql = null;
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = Connections.getConnection();
			sql = "select offsetlat,offsetlng from t_goff_set where lat=round("+la+",2) and lng=round("+lo+",2)";
			rs = this.execute.getRs(sql, conn,stmt);
			if (rs.next()) {
				lalo[0]=rs.getString("offsetlat");
				lalo[1]=rs.getString("offsetlng");
			}
			rs = null;
			sql = "select offsetlat,offsetlng from t_boff_set where lat=round("+la+",2) and lng=round("+lo+",2)";
			rs = this.execute.getRs(sql, conn,stmt);
			if (rs.next()) {
				lalo[2]=rs.getString("offsetlat");
				lalo[3]=rs.getString("offsetlng");
			}
			} catch (Exception e) {
				logger.info("SHW#" + sql);
				e.printStackTrace();
			} finally {
				if (rs != null)
					rs.close();
				if(stmt!=null)
				stmt.close();
				Connections.close(conn);
			}
		return lalo;
	}

	public  void run() {
		String[] sql = null;
		while (true) {
			boolean downFlag=false;
			try {
				Thread.sleep(this.interval);
				if (this.msglist.size() > 0) {
					this.msg = (Event) this.msglist.remove(0);
					int intNum = Integer.parseInt(msg.getProNum(),16);
					switch (intNum) {
					case 129:// gps地址 81
						sql = new String[1];
					//	String[] lalo=getLALO(msg.getLatitude(), msg.getLongitude());
						sql[0] = "INSERT INTO T_GPS_INFO(TERMINAL,SERIALNO,LENGTHS,DATETIMES,LATITUDE,LONGITUDE,STATUSBITS,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getLatitude()
								+ "','"
								+ msg.getLongitude()
								+ "','"
								/*+ msg.getLatitude()+"'+"+lalo[2]
								+ ",'"
								+ msg.getLongitude()+"'+"+lalo[3]
								+ ",'"
								+ msg.getLatitude()+"'+"+lalo[0]
								+ ",'"
								+ msg.getLongitude()+"'+"+lalo[1]
								+ ",'"*/
								+ msg.getStatusBits()
								+ "','"
								+ msg.getProNum()
								+ "')";
						Calendar nowtime = Calendar.getInstance();
						nowtime.add(Calendar.MINUTE, 6);
						if(StringTools.getDateByStr(msg.getDateTime()).compareTo(nowtime.getTime())>0){
							logger.error("SHW# 日期时间有误" +sql[0]);
							continue;
						}
						//从runtimeLALO获取对应终端的初始值不为0，则进行飘移检测
						if((runtimeLALO.get(msg.getTerID())).compareTo(ConfigManager.bd)!=0){
							//经度纬度之和减去初始值大于精确度*上传间隔（1秒为0.0005度），则视为无效飘移数据日志记录，不入库
							if(((StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude())).subtract(runtimeLALO.get(msg.getTerID()))).compareTo(ConfigManager.jqd.multiply(new BigDecimal(TerServer.terTable.get(msg.getTerID())))) ==1){
								runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
								logger.error("SHW# 距离飘移有误" +sql[0]);
								continue;
							}
							runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
						}
						runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
						break;
					case 130:// 基站 82
						sql = new String[1];
						sql[0] = "INSERT INTO T_BASE_STATION(TERMINAL,SERIALNO,LENGTHS,DATETIMES,BASESTATION,STATUSBITS,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getStation()
								+ "','"
								+ msg.getStatusBits()
								+ "','"
								+ msg.getProNum() + "')";
						break;
					case 131:// 目标地址 下行 83
						sql = new String[1];
						/*sql[0] = "INSERT INTO T_TARGET_LOCATION(TERMINAL,SERIALNO,MARK,TYPENO,DATETIMES,STATUS) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ",'"
								+ msg.getIsSuccess()
								+ "','"
								+ msg.getProNum()
								+ "','"
								+ TimeTool.getDateTimeSecond() + "','1')";*/
						sql[1] = "UPDATE T_TARGET_LOCATION status =2,contents='"+msg.getContents()+"' WHERE TERMINAL='"
								+ msg.getTerID()
								+ "' status=0 AND SERIALNO="
								+ msg.getSerNum();
						break;
					case 132:// 心率 84
						sql = new String[1];
						sql[0] = "INSERT INTO T_HEART_RATE(TERMINAL,SERIALNO,LENGTHS,DATETIMES,HEARTRATE,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getHeartRate()
								+ "','"
								+ msg.getProNum()
								+ "')";
						break;
					case 133:// 心电图 85
						sql = new String[1];
						sql[0] = "INSERT INTO T_ECG(TERMINAL,SERIALNO,LENGTHS,DATETIMES,POINTS0x,POINTS,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getEcgContent0x()
								+ "','"
								+ msg.getEcgContent()
								+ "','"
								+ msg.getProNum()
								+ "')";
						break;
					case 134:// 计步器 86
						sql = new String[1];
						sql[0] = "INSERT INTO T_PEDOMETER(TERMINAL,SERIALNO,LENGTHS,DATETIMES,STEPS,DISTANCE,CALORIE,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "',"
								+ msg.getSteps()
								+ ","
								+ msg.getDistance()
								+ ","
								+ msg.getCalorie()
								+ ",'"
								+ msg.getProNum()
								+ "')";
						break;
					case 135:// 血压 87
						sql = new String[1];
						sql[0] = "INSERT INTO T_BLOOD_PRESSURE(TERMINAL,SERIALNO,LENGTHS,DATETIMES,SYSTOLIC,DIASTOLIC,HEARTRATE,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "',"
								+ msg.getSystolic()
								+ ","
								+ msg.getDiastolic()
								+ ","
								+ msg.getHeartRate()
								+ ",'"
								+ msg.getProNum()
								+ "')";
						break;
					case 65:// gps数据41
						sql = new String[1];
//						String[] lalo1=getLALO(msg.getLatitude(), msg.getLongitude());
						sql[0] = "INSERT INTO T_GPS_INFO(TERMINAL,SERIALNO,LENGTHS,DATETIMES,LATITUDE,LONGITUDE,STATUSBITS,TYPENO,RESERVATION,VELOCITY,COURSE,RESERVATIONINFO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getInfoLength()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getLatitude()
								+ "','"
								+ msg.getLongitude()
								+ "','"
								/*+ msg.getLatitude()+"+"+lalo1[2]
										+ "','"
										+ msg.getLongitude()+"+"+lalo1[3]
										+ "','"
										+ msg.getLatitude()+"+"+lalo1[0]
										+ "','"
										+ msg.getLongitude()+"+"+lalo1[1]
								+ "','"*/
								+ msg.getStatusBits()
								+ "','"
								+ msg.getProNum()
								+ "','"
								+ msg.getReservation()
								+ "',"
								+ msg.getVelocity()
								+ ","
								+ msg.getCourse()
								+ ",'" + msg.getTargetReservation() + "')";
						Calendar nowtimes = Calendar.getInstance();
						nowtimes.add(Calendar.MINUTE, 6);
						if(StringTools.getDateByStr(msg.getDateTime()).compareTo(nowtimes.getTime())>0){
							logger.error("SHW# 日期时间有误" +sql[0]);
							continue;
						}
						//从runtimeLALO获取对应终端的初始值不为0，则进行飘移检测
						if((runtimeLALO.get(msg.getTerID())).compareTo(ConfigManager.bd)!=0){
							//经度纬度之和减去初始值大于精确度*上传间隔（1秒为0.0005度），则视为无效飘移数据日志记录，不入库
							if(((StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude())).subtract(runtimeLALO.get(msg.getTerID()))).compareTo(ConfigManager.jqd.multiply(new BigDecimal(TerServer.terTable.get(msg.getTerID())))) ==1){
								runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
								logger.error("SHW# 距离飘移有误" +sql[0]);
								continue;
							}
							runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
						}
						runtimeLALO.put(msg.getTerID(),StringTools.getBigDecimalSum(msg.getLatitude(), msg.getLongitude()));
						break;
					case 66:// 心跳包 42
						sql = new String[1];
						sql[0] = "INSERT INTO T_HEART_BEAT(TERMINAL,SERIALNO,VOLTAGE,SINGAL,DATETIMES,TYPENO) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getSerNum()
								+ ","
								+ msg.getVoltage()
								+ ","
								+ msg.getSignal()
								+ ",'"
								+ msg.getDateTime()
								+ "','"
								+ msg.getProNum() + "')";
						break;
					case 67:// gps数据区间 下行 43
						sql = new String[1];
						/*sql[0] = "INSERT INTO T_GPS_SETTING(TERMINAL,RESERVATION,MARK,TYPENO,DATETIMES,STATUS) VALUES('"
								+ msg.getTerID()
								+ "',"
								+ msg.getReservation()
								+ ",'"
								+ msg.getIsSuccess()
								+ "','"
								+ msg.getProNum()
								+ "','"
								+ TimeTool.getDateTimeSecond() + "','1')";*/
						sql[1] = "UPDATE T_GPS_SETTING status =2,contents='"+msg.getContents()+"' WHERE TERMINAL='"
								+ msg.getTerID() + "' and status=0";
						break;
					case 0:// 连接指令 00
					case 1:// 设置时区 01
					case 2:// 设置GPS时间校准 02
					case 3:// 设置闹铃 03
					case 4:// 设置速度 04
					case 5:// 设置高度 05
					case 6:// 设置温度 06
					case 7:// 设置气压 07
					case 8:// 设置LCD亮度和对比度 08
					case 9:// 设置SOS号码 09
					case 10:// 设置海拔高度 0a
					case 11:// 设置GPS记录时间间隔 0b
					case 12:// 设置固定导航点 0c
					case 13:// 设置导航线路 0d
					case 14:// 设置短信中心号码 0e
					case 15:// 设置用户密码 0f
					case 16:// 设置Tracker下GPRS发送时间 10
					case 17:// 设置Tracker下GPS采集时间间隔 11
					case 18:// 12
						
					case 19:// 13
						
					case 20:// 14
						
					case 21:// 15
					
					case 22:// 16
						
					case 23:// 17
						
					case 24:// 设置用户身高 18
					case 25:// 设置用户体重 19
					case 26:// 设置计步器灵敏度 1a
					case 27:// GPS Track recond数据上传 1b
						if (msg.getDirection().equals("03")) {
							sql = new String[1];
							if(msg.getContents().equals("01")){
								sql[0]="UPDATE T_UPPER_INFO SET STATUS=2 WHERE TERMINAL='"+msg.getTerID()+"' AND STATUS=0 AND DIRECTION='01' AND TYPENO='"+msg.getProNum()+"'";
							}else{
								sql[0]="UPDATE T_UPPER_INFO SET STATUS=1 WHERE TERMINAL='"+msg.getTerID()+"' AND STATUS=0 AND DIRECTION='01' AND TYPENO='"+msg.getProNum()+"'";
							}
							
						} else if (msg.getDirection().equals("02")) {
							sql = new String[1];
							sql[0]="UPDATE T_UPPER_INFO SET STATUS=2,CONTENTS='"+msg.getContents()+"' WHERE TERMINAL='"+msg.getTerID()+"' AND STATUS=0 AND DIRECTION='00'";
//							sql[1]="INSERT INTO T_UPPER_INFO (TERMINAL,TYPENO,DIRECTION,LENGTHS,CONTENTS,CONTENTS0X,DATETIMES,STATUS) VALUES('"+msg.getTerID()+"','"+msg.getProNum()+"','"+msg.getDirection()+"',"+msg.getInfoLength()+",'"+msg.getContents()+"','"+msg.getContents0x()+"','"+ TimeTool.getDateTimeSecond() + "','2')";
						}
						downFlag=true;
						break;
					default:
						break;
					}
					this.extuteSql(sql,downFlag);
				}
			} catch (Exception e) {
				logger.info("SHW#" + e.getMessage());
				e.printStackTrace();
			}
		}
	}

	/*
	 * @Override protected void executeEvent(Event paramEvent) { String[] sql =
	 * new String[1]; if (paramEvent != null){ try { sql[0]="";
	 * this.extuteSql(sql); } catch (Exception e) { e.printStackTrace(); } }
	 * logger.info("添加信息~~~~~~~~~~~~~~~~~~~~~~"); }
	 */
	public static void main(String args[]) throws Exception{
		//Connection con=Connections.getConnection();
		//Statement stmt=con.createStatement();
		String sql="select latitude,longitude from t_gps_info order by datetimes";
		//ResultSet rs=stmt.executeQuery(sql);
		int i=0;
		BigDecimal bd=new BigDecimal(0);
		ExecuteThread.runtimeLALO.put("123456",new BigDecimal(0));
		String[] a={"34.24211","108.89706166666667"};
		String[] b={"34.24207833333333","108.89722333333333"};
		//String[] c={"34.24095433","108.901810333"};
		ArrayList<String[]> list=new ArrayList<String[]>();
		list.add(a);list.add(b);//list.add(c);
		for(String[] obj:list ){
//			BigDecimal bd1=new BigDecimal(rs.getString(1));
//			BigDecimal bd2=new BigDecimal(rs.getString(2));
			String bd1=obj[0];
			String bd2=obj[1];
			
			if((ExecuteThread.runtimeLALO.get("123456")).compareTo(ConfigManager.bd)!=0){
				//经度纬度之和减去初始值大于精确度*上传间隔（1秒为0.0005度），则视为无效飘移数据日志记录，不入库
				BigDecimal bbd=(StringTools.getBigDecimalSum(bd1,bd2)).subtract(ExecuteThread.runtimeLALO.get("123456"));
						BigDecimal ddb=ConfigManager.jqd.multiply(new BigDecimal(10));
						if((bbd).compareTo(ddb) ==1){
					ExecuteThread.runtimeLALO.put("123456",StringTools.getBigDecimalSum(bd1, bd2));
					logger.error("SHW# 距离飘移有误" +bd1+"   "+bd2);
					continue;
				}
				ExecuteThread.runtimeLALO.put("123456",StringTools.getBigDecimalSum(bd1, bd2));
			}
			ExecuteThread.runtimeLALO.put("123456",StringTools.getBigDecimalSum(bd1, bd2));
		}
	}
}